# -*- coding: utf-8 -*-
from django import forms

from servico.models import ServicoInterno, Equipe, MaterialServico,\
    EquipeExecutante, ServicoStatus
from djtools.formfields import BrDataField, BrHoraField
from djtools.formwidgets import BrDataWidget, BrTimeWidget
from comum.models import Estacao, Setor
from datetime import datetime
from django.db.models import Max

###########
# SERVIÇO #
###########

class ServicoInternoForm(forms.ModelForm):
    class Meta:
        model = ServicoInterno
    
    def save(self, commit=True, force_insert=False, force_update=False):
        if self.instance.pk is None:
            get_pk = ServicoInterno.objects.aggregate(Max('pk'))
            if get_pk['pk__max']:
                get_id = get_pk['pk__max'] + 1
            else:
                get_id = 1
            get_setor = self.instance.setor.sigla
            get_data = self.instance.data_emissao.strftime("%m%y")
            mont_numero = "%s/%s/%s" % (get_id, get_setor, get_data)
            self.instance.numero = mont_numero
        return super(ServicoInternoForm, self).save(commit)
    
    status = forms.ModelChoiceField(label=u'Status', queryset=ServicoStatus.objects.all())
    setor = forms.ModelChoiceField(label=u'Setor Solicitante', queryset=Setor.objects.all())
    numero = forms.CharField(label=u'Número', widget=forms.TextInput(attrs={'readonly':'readonly'}), required=False)
    estacao = forms.ModelChoiceField(label=u'Estação', queryset=Estacao.objects.all())
    data_emissao = BrDataField(label=u'Data de Emissão', widget=BrDataWidget(), initial=datetime.now())
    data_inicio = BrDataField(label=u'Data do Início', widget=BrDataWidget(), required=False)
    data_conclusao = BrDataField(label=u'Data Conclusão', widget=BrDataWidget(), required=False)
    
class MaterialServicoForm(forms.ModelForm):
    class Meta:
        model = MaterialServico

    fieldsets = [
         ('Materiais', {'fields': [('servico'),('descricao'), ('cod_material', 'quantidade', 'unidade')]}),
                 ]

    def __init__(self, *args, **kwargs):
        servico_id = kwargs.pop('servico_id')
        servico = ServicoInterno.objects.get(id=servico_id)
        super(MaterialServicoForm, self).__init__(*args, **kwargs)
        self.fields['servico'].initial = servico.id

    servico = forms.ModelChoiceField(queryset=ServicoInterno.objects.all(), widget=forms.HiddenInput())
    descricao = forms.CharField(label=u'Descrição', max_length=250, widget=forms.TextInput(attrs={'size':'104'}))
    cod_material = forms.CharField(label=u'Código', max_length=100, widget=forms.TextInput(attrs={'size':'7'}))
    quantidade = forms.CharField(label=u'Quantidade', max_length=100, widget=forms.TextInput(attrs={'size':'7'}))
    unidade = forms.CharField(label=u'Unidade', max_length=100, widget=forms.TextInput(attrs={'size':'7'}))

class EquipeExecutanteForm(forms.ModelForm):
    class Meta:
        model = EquipeExecutante

    fieldsets = [
        (None, {'fields': [('servico'), 'nome', 'data']}),
        (None, {'fields': [('mhora_inicio', 'mhora_termino'), ('thora_inicio', 'thora_termino'), 'hora_total', ('xhora_inicio', 'xhora_termino', 'xhora_total')]}),
                ]

    def __init__(self, *args, **kwargs):
        servico_id = kwargs.pop('servico_id')
        servico = ServicoInterno.objects.get(id=servico_id)
        super(EquipeExecutanteForm, self).__init__(*args, **kwargs)
        self.fields['servico'].initial = servico.id

    servico = forms.ModelChoiceField(queryset=ServicoInterno.objects.all(), widget=forms.HiddenInput())
    nome = forms.CharField(label=u'Nome', max_length=250, widget=forms.TextInput(attrs={'size':'70'}))
    data = BrDataField(label=u'Data', widget=BrDataWidget())
    mhora_inicio = BrHoraField(label=u'Matutino', help_text=u'Data de início', required=False)
    mhora_termino = BrHoraField(help_text=u'Data de termino', widget=BrTimeWidget(show_label=False), required=False)
    thora_inicio = BrHoraField(label=u'Vespertino', help_text=u'Data de início', required=False)
    thora_termino = BrHoraField(help_text=u'Data de termino', widget=BrTimeWidget(show_label=False), required=False)
    hora_total = BrHoraField(label=u'Horas Totais', required=False)
    xhora_inicio = BrHoraField(label=u'Horas Extras', help_text=u'Data de início', required=False)
    xhora_termino = BrHoraField(help_text=u'Data de termino', widget=BrTimeWidget(show_label=False), required=False)
    xhora_total = BrHoraField(label=u'Horas Extras Totais', required=False)